﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace ClientRegister
{
    public class SynchronizeData
    {
        public string insertMethod = "Insert";
        public string updateMethod = "Update";
        public string deleteMethod = "Delete";

        public string ClassOfStu = "StudentInClass";
        public string studentTb = "Students";
        public string ClassTb = "Classes";
        public string ClassInCourTb = "ClassInCourse";
        public string CourTb = "Courses";
        public string EmployTb = "Employees";
        public string RoomTb = "Rooms";
        public string SubInCourTb = "SubjectInCourse";
        public string SubTb = "Subjects";
        public string TeacherTb = "Teachers";
        public string TeacherTeachTb = "TeacherTeach";

        string clientSign = "100";

        ConnectDB con = new ConnectDB();
        SqlConnection cnn;
        SqlCommand cmd, cmd2, cmd3;
        //SqlDataAdapter ada;

        //Kiem tra mot record co ton tai trong table hay ko sung dung cho bang co CreateDateTime khac nhau
        public int CheckExist(string table, string field, string data)
        {
            SqlConnection cnn1;
            SqlCommand cmd1;
            SqlDataAdapter ada1;

            string query = string.Format("select {1} from {0} where {1} = '{2}'", table, field, DateTime.Parse(data));
            cnn1 = con.Connect();
            cnn1.Open();
            cmd1 = new SqlCommand(query, cnn1);
            ada1 = new SqlDataAdapter(cmd1);
            DataSet ds = new DataSet();
            ada1.Fill(ds);
            int check = ds.Tables[0].Rows.Count;
            cnn1.Close();
            return check;
        }
        //Kiem tra 1 record co ton tai trong table hay ko, dung trong bang co nhieu CreateDateTime giong nhau
        public int CheckExistId(string table, string FieldId1, string FieldId2, string Id1, string Id2)
        {
            SqlConnection cnn1;
            SqlCommand cmd1;
            SqlDataAdapter ada1;

            string query = string.Format("select * from {0} where {1} = '{2}' and {3} = '{4}'", table, FieldId1, Id1, FieldId2, Id2);
            cnn1 = con.Connect();
            cnn1.Open();
            cmd1 = new SqlCommand(query, cnn1);
            ada1 = new SqlDataAdapter(cmd1);
            DataSet ds = new DataSet();
            ada1.Fill(ds);
            int check = ds.Tables[0].Rows.Count;
            cnn1.Close();
            return check;
        }

        //chuyen thong tin tac vu Insert len server
        public void transfDataForInsertMethod(string xml, string table)
        {
            Service.RegisterService trans = new Service.RegisterService();
            trans.SendXmlString(table, xml, insertMethod, clientSign);
        }
        //chuyen thong tin tac vu Update len server
        public void transfDataForUpdateMethod(string xml, string table)
        {
            Service.RegisterService trans = new Service.RegisterService();
            trans.SendXmlString(table, xml, updateMethod, clientSign);
        }
        //chuyen thong tin tac vu Delete len server
        public void transfDataForDeleteMethod(string xml, string table)
        {
            Service.RegisterService trans = new Service.RegisterService();
            trans.SendXmlString(table, xml, deleteMethod, clientSign);
        }
        //=================================================================================================//
        //Nhan du lieu tu Server
        //=============================================================================================//
        //Convert xml to Dataset
        public void ModifyDataForMethodWithID(string xml, string column)
        {
            //Conver xmlstring to dataset
            if (xml != "")
            {
                StringReader strReader = null;
                XmlTextReader xmltxtReader = null;
                DataSet ds;
                try
                {
                    ds = new DataSet();
                    strReader = new StringReader(xml);

                    //load xmltxtReader from strReader
                    xmltxtReader = new XmlTextReader(strReader);
                    ds.ReadXml(xmltxtReader);
                }
                finally
                {
                    if (xmltxtReader == null) xmltxtReader.Close();
                }
                //===============================================
                // sync client
                ModifyDataSetForMethodWithID(ds, column);
            }
        }

        public void ModifyDataSetForMethodWithID(DataSet ds, string column)
        {

            int col = ds.Tables[0].Columns.Count;
            int row = ds.Tables[0].Rows.Count;
            string name = ds.Tables[0].TableName;
            string fields = "";

            for (int i = 0; i < ds.Tables[name].Columns.Count; i++)
            {
                if (i == 0)
                    fields += ds.Tables[name].Columns[i].ColumnName;
                else fields += "," + ds.Tables[name].Columns[i].ColumnName;
            }
            string[] str_fields = fields.Split(',');
            ArrayList arr_rec = new ArrayList();

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    arr_rec.Add(ds.Tables[name].Rows[i].ItemArray[j]);
                }
            }
            //insert table into database
            ModifyTableForMethodWithID(arr_rec, name, str_fields, column);
            arr_rec.Clear();
        }

        public void ModifyTableForMethodWithID(ArrayList arr_data, string tableName, string[] fields, string column)
        {
            string queryInsert, queryUpdate, queryDelete, str_param;
            string fieldtable = string.Join(",", fields);
            //Chuoi query cho command Update
            string[] fieldsUpdatearr = new string[fields.Length];
            for (int i = 0; i < fields.Length; i++)
            {
                fieldsUpdatearr[i] = fields[i] + " = @" + fields[i];
            }

            string fieldsUpdate = string.Join(",", fieldsUpdatearr);

            //=============================================================================
            //Chuoi query cho command insert
            for (int i = 0; i < fields.Length; i++)
            {
                fields[i] = "@" + fields[i];
            }
            str_param = string.Join(",", fields);
            queryInsert = "insert into " + tableName + "(" + fieldtable + ") values(" + str_param + ")";
            //=======================================================================================



            int row = arr_data.Count / fields.Length;
            int pos = 0;
            for (int j = 0; j < row; j++)
            {
                cnn = con.Connect();
                cmd = new SqlCommand(queryInsert, cnn);

                cmd2 = new SqlCommand();
                cmd2.Connection = cnn;

                cmd3 = new SqlCommand();
                cmd3.Connection = cnn;
                
                string IdRecod = "";
                string LastUpdate = "";

                int k = 0;

                for (int i = pos; i < arr_data.Count; i++)
                {
                    cmd.Parameters.AddWithValue(fields[k], arr_data[i]);
                    cmd2.Parameters.AddWithValue(fields[k], arr_data[i]);

                    if(k == 0) IdRecod = arr_data[i].ToString();
                    if (fields.Length - k == 2) LastUpdate = arr_data[i].ToString();

                    k++;
                    pos++;
                    //Can kiem tra xem record co ton tai trong table truoc khi insert
                    if (k == fields.Length)
                    {
                        string CreateCol = "CreateDateTime";
                        // cot du lieu InsertData
                        if (column == insertMethod)
                        {
                            if (CheckExist(tableName, CreateCol, arr_data[i].ToString()) == 0)
                            {
                                cnn.Open();
                                cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                                cnn.Close();
                                break;
                            }
                            else break;
                        }
                        //Cot du lieu UpdateData
                        else if (column == updateMethod)
                        {
                            queryUpdate = "update " + tableName + " set " + fieldsUpdate + " where " + CreateCol + " = '" + arr_data[i] + "' and (LastUpdate IS NULL or LastUpdate < '" + LastUpdate + "')";
                            cmd2.CommandText = queryUpdate;
                            cnn.Open();
                            cmd2.ExecuteNonQuery();
                            cmd2.Parameters.Clear();
                            cnn.Close();
                            break;
                        }
                        //Cot due lieu DeleteData
                        else
                        {
                            queryDelete = "delete from " +tableName+ " where ID = '" +IdRecod+ "'";
                            cmd3.CommandText = queryDelete;
                            cnn.Open();
                            cmd3.ExecuteNonQuery();
                            cmd3.Parameters.Clear();
                            cnn.Close();
                            break;
                        }
                        //reset field
                        cmd.Parameters.Clear();
                        cmd2.Parameters.Clear();
                        cmd3.Parameters.Clear();
                        k = 0;
                    }
                    //==================================================================
                }
            }


        }

        public void GetDataForInsertMethodWithID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForMethodWithID(xml, method);
        }

        public void GetDataForUpdateMethodWithID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForMethodWithID(xml, method);
        }

        public void GetDataForDeleteMethodWithID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForMethodWithID(xml, method);
        }



        //==============================================================================================
        //===========Ham Modify cho nhung table co nhieu CreateDateTime giong nhau======================
        //Convert xml to Dataset
        public void ModifyDataForInsertMethodWithNoneID(string xml, string method)
        {
            //Conver xmlstring to dataset
            if (xml != "")
            {
                StringReader strReader = null;
                XmlTextReader xmltxtReader = null;
                DataSet ds;
                try
                {
                    ds = new DataSet();
                    strReader = new StringReader(xml);

                    //load xmltxtReader from strReader
                    xmltxtReader = new XmlTextReader(strReader);
                    ds.ReadXml(xmltxtReader);
                }
                finally
                {
                    if (xmltxtReader == null) xmltxtReader.Close();
                }
                //===============================================
                // sync client
                ModifyDataSetForInsertMethodWithNoneID(ds, method);
            }
        }
        //===============================================================
        public void ModifyDataSetForInsertMethodWithNoneID(DataSet ds, string method)
        {

            int col = ds.Tables[0].Columns.Count;
            int row = ds.Tables[0].Rows.Count;
            string name = ds.Tables[0].TableName;
            string fields = "";

            for (int i = 0; i < ds.Tables[name].Columns.Count; i++)
            {
                if (i == 0)
                    fields += ds.Tables[name].Columns[i].ColumnName;
                else fields += "," + ds.Tables[name].Columns[i].ColumnName;
            }
            string[] str_fields = fields.Split(',');
            ArrayList arr_rec = new ArrayList();

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    arr_rec.Add(ds.Tables[name].Rows[i].ItemArray[j]);
                }
            }
            //insert table into database
            ModifyTableForInsertMethodWithNoneID(arr_rec, name, str_fields, method);
            arr_rec.Clear();
        }
        //=====================================================================
        public void ModifyTableForInsertMethodWithNoneID(ArrayList arr_data, string tableName, string[] fields, string method)
        {
            string queryInsert, queryDelete,str_param;
            string fieldtable = string.Join(",", fields);

            //Chuoi query cho command Update
            //Gan ten cua 2 cot ID
            string fieldId1 = fields[0];
            string fieldId2 = fields[1];

            //=============================================================================
            //Chuoi query cho command insert
            for (int i = 0; i < fields.Length; i++)
            {
                fields[i] = "@" + fields[i];
            }
            str_param = string.Join(",", fields);
            queryInsert = "insert into " + tableName + "(" + fieldtable + ") values(" + str_param + ")";
            //=======================================================================================

            cnn = con.Connect();
            int row = arr_data.Count / fields.Length;
            int pos = 0;
            for (int j = 0; j < row; j++)
            {

                cmd = new SqlCommand(queryInsert, cnn);
                
                cmd3 = new SqlCommand();
                cmd3.Connection = cnn;

                string id1 = "", id2 = "";
                int k = 0;

                for (int i = pos; i < arr_data.Count; i++)
                {
                    cmd.Parameters.AddWithValue(fields[k], arr_data[i]);

                    //Gan gia tri Id cho bien
                    if (k == 0) id1 = arr_data[i].ToString();
                    if (k == 1) id2 = arr_data[i].ToString();
                    k++;
                    pos++;
                    //Can kiem tra xem record co ton tai trong table truoc khi insert
                    if (k == fields.Length)
                    {
                        //string CreateCol = "CreateDateTime";
                        // cot du lieu InsertData
                        if (method == insertMethod)
                        {
                            if (CheckExistId(tableName, fieldId1, fieldId2, id1, id2) == 0)
                            {
                                cnn.Open();
                                cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                                cnn.Close();
                                break;
                            }
                            else break;
                        }
                        else if (method == deleteMethod)
                        {
                            queryDelete = string.Format("delete from {0} where {1} = '{3}' and {2} = '{4}'",tableName, fieldId1, fieldId2, id1, id2);
                            cmd3.CommandText = queryDelete;
                            cnn.Open();
                            cmd3.ExecuteNonQuery();
                            cmd3.Parameters.Clear();
                            cnn.Close();
                            break;
                        }
                        //reset field
                        cmd.Parameters.Clear();
                        cmd3.Parameters.Clear();
                    }
                    //==================================================================
                }
            }
        }
        //===================================================================================
        public void GetDataForInsertMethodWithNoneID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForInsertMethodWithNoneID(xml, method);
        }

        //===================================================================================
        //Convert xml to Dataset
        public void ModifyDataForUpdateMethodWithNoneID(string xml, string method)
        {
            //Conver xmlstring to dataset
            if (xml != "")
            {
                StringReader strReader = null;
                XmlTextReader xmltxtReader = null;
                DataSet ds;
                try
                {
                    ds = new DataSet();
                    strReader = new StringReader(xml);

                    //load xmltxtReader from strReader
                    xmltxtReader = new XmlTextReader(strReader);
                    ds.ReadXml(xmltxtReader);
                }
                finally
                {
                    if (xmltxtReader == null) xmltxtReader.Close();
                }
                //===============================================
                // sync client
                ModifyDataSetForUpdateMethodWithNoneID(ds, method);
            }
        }

        //===============================================================
        public void ModifyDataSetForUpdateMethodWithNoneID(DataSet ds, string method)
        {

            int col = ds.Tables[0].Columns.Count;
            int row = ds.Tables[0].Rows.Count;
            string name = ds.Tables[0].TableName;
            string fields = "";

            for (int i = 0; i < ds.Tables[name].Columns.Count; i++)
            {
                if (i == 0)
                    fields += ds.Tables[name].Columns[i].ColumnName;
                else fields += "," + ds.Tables[name].Columns[i].ColumnName;
            }
            string[] str_fields = fields.Split(',');
            ArrayList arr_rec = new ArrayList();

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    arr_rec.Add(ds.Tables[name].Rows[i].ItemArray[j]);
                }
            }
            //insert table into database
            ModifyTableForForUpdateMethodWithNoneID(arr_rec, name, str_fields, method);
            arr_rec.Clear();
        }

        public void ModifyTableForForUpdateMethodWithNoneID(ArrayList arr_data, string tableName, string[] fields, string method)
        {
            string queryUpdate;
            string fieldtable = string.Join(",", fields);
            //Chuoi query cho command Update
            string[] fieldsUpdatearr = new string[fields.Length];
            for (int i = 0; i < fields.Length; i++)
            {
                fieldsUpdatearr[i] = fields[i] + " = @" + fields[i];
            }

            //Gan ten cua 2 cot ID
            string fieldId1 = fields[0];
            string fieldIdOld = fields[2];

            string fieldsUpdate = string.Join(",", fieldsUpdatearr);

            //=============================================================================
            //=======================================================================================

            cnn = con.Connect();

            int pos = 0, k = 0;
            queryUpdate = "update " + tableName + " set " + fieldsUpdate;

            cmd2 = new SqlCommand();
            cmd2.Connection = cnn;

            string id1 = "", idold = "", LastUpdate = "";
            for (int i = pos; i < arr_data.Count; i++)
            {
                //Gan 2 Id cua record co du lieu thay doi
                if (k == 0) id1 = arr_data[i].ToString();
                if (k == 2) idold = arr_data[i].ToString();

                if (fields.Length - k == 2) LastUpdate = arr_data[i].ToString();

                cmd2.Parameters.AddWithValue(fields[k], arr_data[i]);
                k++;
                pos++;
                if (k == fields.Length)
                {
                    //Cot du lieu UpdateData
                    if (method == updateMethod)
                    {
                        queryUpdate += " where " + fieldId1 + " = '" + id1 + "' and " + fieldIdOld + " = '" + idold + "' and (LastUpdate IS NULL or LastUpdate < '" + LastUpdate + "')";
                        cmd2.CommandText = queryUpdate;
                        cnn.Open();
                        cmd2.ExecuteNonQuery();
                        cmd2.Parameters.Clear();
                        cnn.Close();
                    }
                    //reset field
                    cmd2.Parameters.Clear();
                    k = 0;
                }
                //==================================================================
            }
            cnn.Close();
        }

        public void GetDataForUpdateMethodWithNoneID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForUpdateMethodWithNoneID(xml, method);
        }

        public void GetDataForDeleteMethodWithNoneID(string tbName, string method)
        {
            Service.RegisterService getdata = new Service.RegisterService();
            string xml = getdata.GetXmlString(tbName, method, clientSign);
            ModifyDataForInsertMethodWithNoneID(xml, method);
        }


        //=================================================================================================
        //==============================Chuyen du lieu len server==========================================
        //=================================================================================================
        public void transDataToServer()
        {
            //Chuyen thong tin NV=======================================
            //Insert thong tin nhan vien
            string InsEmpXml = "", UpEmpXml = "";
            EmployeesDataProvider emp = new EmployeesDataProvider();
            DataSet dsEmp = emp.SelectIDNewRecord();
            emp.UpdateNewRecord();
            DataTable dtEmp = dsEmp.Tables[0];
            for (int i = 0; i < dtEmp.Rows.Count; i++)
            {
                string IdEmp = dtEmp.Rows[i].ItemArray[0].ToString();
                InsEmpXml += emp.SelectAndConvertXMLEmp(IdEmp);
            }
            transfDataForInsertMethod(InsEmpXml, EmployTb);
            //Update thong tin nhan vien
            DataSet dsUpEmp = emp.SelectIDNewRecordUpdate();
            emp.UpdateNewRecordUpdate();
            DataTable dtUpEmp = dsUpEmp.Tables[0];
            for (int i = 0; i < dtUpEmp.Rows.Count; i++)
            {
                string idEmp = dtUpEmp.Rows[i].ItemArray[0].ToString();
                UpEmpXml += emp.SelectAndConvertXMLEmp(idEmp);
            }
            transfDataForUpdateMethod(UpEmpXml, EmployTb);
            //Delete nhan vien
            string DelEmpXml = "";
            transfDataForDeleteMethod(DelEmpXml, EmployTb);


            //================================================================

            //Chuyen thong tin Mon hoc
            //Insert mon hoc
            string InsSubXml = "";
            SubjectsDataProvider sub = new SubjectsDataProvider();
            DataSet dsSub = sub.SelectIDNewRecord();
            sub.UpdateNewRecord();
            DataTable dtSub = dsSub.Tables[0];
            for (int i = 0; i < dtSub.Rows.Count; i++)
            {
                string idSub = dtSub.Rows[i].ItemArray[0].ToString();
                InsSubXml += sub.SelectAndConvertXMLSub(idSub);
            }
            transfDataForInsertMethod(InsSubXml, SubTb);
            //Update Mon hoc
            string UpSubXml = "";
            DataSet dsUpSub = sub.SelectIDNewRecordUpdate();
            sub.UpdateNewRecordUpdate();
            DataTable dtUpSub = dsUpSub.Tables[0];
            for (int i = 0; i < dtUpSub.Rows.Count; i++)
            {
                string idSub = dtUpSub.Rows[i].ItemArray[0].ToString();
                UpSubXml += sub.SelectAndConvertXMLSub(idSub);
            }
            transfDataForUpdateMethod(UpSubXml, SubTb);
            //Delete Mon hoc
            string DelSubXml = "";
            transfDataForDeleteMethod(DelSubXml, SubTb);
            //======================================================================

            //Chuyen thong tin giao vien
            //Insert giao vien
            string InsTeachXml = "";
            TeacherDataProvider teach = new TeacherDataProvider();
            DataSet dsInTeach = teach.SelectIDNewRecord();
            teach.UpdateNewRecord();
            DataTable dtInTeach = dsInTeach.Tables[0];
            for (int i = 0; i < dtInTeach.Rows.Count; i++)
            {
                string IdTeach = dtInTeach.Rows[i].ItemArray[0].ToString();
                InsTeachXml += teach.SelectAndConvertXMLTech(IdTeach);
            }
            transfDataForInsertMethod(InsTeachXml, TeacherTb);
            //Update giao vien
            string UpTeachXml = "";
            DataSet dsUpTeach = teach.SelectIDNewRecordUpdate();
            teach.UpdateNewRecordUpdate();
            DataTable dtUpTeach = dsUpTeach.Tables[0];
            for (int i = 0; i < dtUpTeach.Rows.Count; i++)
            {
                string idTeach = dtUpTeach.Rows[i].ItemArray[0].ToString();
                UpTeachXml += teach.SelectAndConvertXMLTech(idTeach);
            }
            transfDataForUpdateMethod(UpTeachXml, TeacherTb);
            //Delete giao vien
            string DelTeachXml = "";
            transfDataForDeleteMethod(DelTeachXml, TeacherTb);
            //======================================================================

            //Chuyen thon tin chuyen mon cua giao vien
            //Insert chuyen mon giao vien
            string InsTeacherTeachXml = "";
            TeacherTeachDataProvider teacherteach = new TeacherTeachDataProvider();
            DataSet dsInsTT = teacherteach.SelectIDNewRecord();
            teacherteach.UpdateNewRecord();
            DataTable dtInsTT = dsInsTT.Tables[0];
            for (int i = 0; i < dtInsTT.Rows.Count; i++)
            {
                string idTeach = dtInsTT.Rows[i].ItemArray[0].ToString();
                string idSub = dtInsTT.Rows[i].ItemArray[1].ToString();
                InsTeacherTeachXml += teacherteach.ConvertTeacherTeachToXML(idTeach, idSub);
            }
            transfDataForInsertMethod(InsTeacherTeachXml, TeacherTeachTb);
            //Update chuyen mon giao vien
            string UpTeacherTeachXml = "";
            DataSet dsUpTT = teacherteach.SelectIDNewRecordUpdate();
            teacherteach.UpdateNewRecordUpdate();
            DataTable dtUpTT = dsUpTT.Tables[0];
            for (int i = 0; i < dtUpTT.Rows.Count; i++)
            {
                string idTeacher = dtUpTT.Rows[i].ItemArray[0].ToString();
                string idSub = dtUpTT.Rows[i].ItemArray[1].ToString();
                UpTeacherTeachXml += teacherteach.ConvertTeacherTeachToXML(idTeacher, idSub);
            }
            transfDataForUpdateMethod(UpTeacherTeachXml, TeacherTeachTb);
            //Delete chuyen mon giao vien
            string DelTeacherTeachXml = "";
            transfDataForDeleteMethod(DelTeacherTeachXml, TeacherTeachTb);
            //=======================================================================

            //Chuyen thong tin phong hoc
            //Insert phong hoc
            string InsRoomXml = "";
            RoomDataProvider room = new RoomDataProvider();
            DataSet dsInsRoom = room.SelectIDNewRecord();
            room.UpdateNewRecord();
            DataTable dtInsRoom = dsInsRoom.Tables[0];
            for (int i = 0; i < dtInsRoom.Rows.Count; i++)
            {
                string name = dtInsRoom.Rows[i].ItemArray[0].ToString();
                InsRoomXml += room.SelectAndConvertXMLRoom(name);
            }
            transfDataForInsertMethod(InsRoomXml, RoomTb);
            //Update phong hoc
            string UpRoomXml = "";
            DataSet dsUpRoom = room.SelectIDNewRecordUpdate();
            room.UpdateNewRecordUpdate();
            DataTable dtUpRoom = dsUpRoom.Tables[0];
            for (int i = 0; i < dtUpRoom.Rows.Count; i++)
            {
                string name = dtUpRoom.Rows[i].ItemArray[0].ToString();
                UpRoomXml += room.SelectAndConvertXMLRoom(name);
            }
            transfDataForUpdateMethod(UpRoomXml, RoomTb);
            //Delete phong hoc
            string DelRoomXml = "";
            transfDataForDeleteMethod(DelRoomXml, RoomTb);
            //======================================================================

            //Chuyen thong tin lop hoc
            ClassDataProvider classes = new ClassDataProvider();
            //Insert thong tin lop hoc
            string InsClassXml = "";
            DataSet dsInClass = classes.SelectIDNewRecord();
            classes.UpdateNewRecord();
            DataTable dtInClass = dsInClass.Tables[0];
            for (int i = 0; i < dtInClass.Rows.Count; i++)
            {
                string idClass = dtInClass.Rows[i].ItemArray[0].ToString();
                InsClassXml += classes.ConvertClassToXML(idClass);
            }
            transfDataForInsertMethod(InsClassXml, ClassTb);
            //update thong tin lop hoc
            string UpClassXml = "";
            DataSet dsUpClass = classes.SelectIDNewRecordUpdate();
            classes.UpdateNewRecordUpdate();
            DataTable dtUpClass = dsUpClass.Tables[0];
            for (int i = 0; i < dtUpClass.Rows.Count; i++)
            {
                string idClass = dtUpClass.Rows[i].ItemArray[0].ToString();
                UpClassXml += classes.ConvertClassToXML(idClass);
            }
            transfDataForUpdateMethod(UpClassXml, ClassTb);
            //Delete lop hoc
            string DelClassXml = "";
            transfDataForDeleteMethod(DelClassXml, ClassTb);
            //======================================================================

            //Chuyen thong tin khoa hoc
            CourseDataProvider cour = new CourseDataProvider();
            //Insert thong tin khoa hoc
            string InsCourXml = "";
            DataSet dsInsCour = cour.SelectIDNewRecord();
            cour.UpdateNewRecord();
            DataTable dtInCour = dsInsCour.Tables[0];
            for (int i = 0; i < dtInCour.Rows.Count; i++)
            {
                string idCour = dtInCour.Rows[i].ItemArray[0].ToString();
                InsCourXml += cour.ConvertInfoCourseToXml(idCour);
            }
            transfDataForInsertMethod(InsCourXml, CourTb);
            //Update thong tin khoa hoc
            string UpCourXml = "";
            DataSet dsUpCour = cour.SelectIDNewRecordUpdate();
            cour.UpdateNewRecordUpdate();
            DataTable dtUpCour = dsUpCour.Tables[0];
            for (int i = 0; i < dtUpCour.Rows.Count; i++)
            {
                string idCour = dtUpCour.Rows[i].ItemArray[0].ToString();
                UpCourXml += cour.ConvertInfoCourseToXml(idCour);
            }
            transfDataForUpdateMethod(UpCourXml, CourTb);
            //Delete khoa hoc
            string DelCourXml = "";
            transfDataForDeleteMethod(DelCourXml, CourTb);
            //=======================================================================

            //Chuyen thong tin lop hoc thuoc khoa hoc
            ClassInCourseProvider classInCour = new ClassInCourseProvider();
            //Insert
            string InsClassInCourXml = "";
            DataSet dsInsClassInCour = classInCour.SelectIDNewRecord();
            classInCour.UpdateNewRecord();
            DataTable dtInsClassInCour = dsInsClassInCour.Tables[0];
            for (int i = 0; i < dtInsClassInCour.Rows.Count; i++)
            {
                string idCour = dtInsClassInCour.Rows[i].ItemArray[0].ToString();
                string idClass = dtInsClassInCour.Rows[i].ItemArray[1].ToString();
                InsClassInCourXml += classInCour.selectClassInCourse(idCour, idClass);
            }
            transfDataForInsertMethod(InsClassInCourXml, ClassInCourTb);
            //Update
            string UpClassInCourXml = "";
            DataSet dsUpClassInCour = classInCour.SelectIDNewRecordUpdate();
            classInCour.UpdateNewRecordUpdate();
            DataTable dtUpClassInCour = dsUpClassInCour.Tables[0];
            for (int i = 0; i < dtUpClassInCour.Rows.Count; i++)
            {
                string idCour = dtUpClassInCour.Rows[i].ItemArray[0].ToString();
                string idClass = dtUpClassInCour.Rows[i].ItemArray[1].ToString();
                UpClassInCourXml += classInCour.selectClassInCourse(idCour, idClass);
            }
            transfDataForUpdateMethod(UpClassInCourXml, ClassInCourTb);
            //Delete
            string DelClassInCourXml = "";
            transfDataForDeleteMethod(DelClassInCourXml, ClassInCourTb);
            //=======================================================================

            //Chuyen thong tin Mon hoc thuoc khoa hoc
            SubjectInCourse subInCour = new SubjectInCourse();
            //Insert
            string InsSubInCourXml = "";
            DataSet dsInsSubInCour = subInCour.SelectIDNewRecord();
            subInCour.UpdateNewRecord();
            DataTable dtInsSubInCour = dsInsSubInCour.Tables[0];
            for (int i = 0; i < dtInsSubInCour.Rows.Count; i++)
            {
                string idSub = dtInsSubInCour.Rows[i].ItemArray[0].ToString();
                string idCour = dtInsSubInCour.Rows[i].ItemArray[1].ToString();
                InsSubInCourXml += subInCour.ConvertSubInCourseToXML(idCour, idSub);
            }
            transfDataForInsertMethod(InsSubInCourXml, SubInCourTb);
            //Update
            string UpSubInCourXml = "";
            DataSet dsUpSubInCour = subInCour.SelectIDNewRecordUpdate();
            subInCour.UpdateNewRecordUpdate();
            DataTable dtUpSubInCour = dsUpSubInCour.Tables[0];
            for (int i = 0; i < dtUpSubInCour.Rows.Count; i++)
            {
                string idSub = dtUpSubInCour.Rows[i].ItemArray[0].ToString();
                string idCour = dtUpSubInCour.Rows[i].ItemArray[1].ToString();
                UpSubInCourXml += subInCour.ConvertSubInCourseToXML(idCour, idSub);
            }
            transfDataForUpdateMethod(UpSubInCourXml, SubInCourTb);
            //Delete
            string DelSubInCourXml = "";
            transfDataForDeleteMethod(DelSubInCourXml, SubInCourTb);
            //========================================================================

            //Chuyen thong tin hoc vien
            StudentDataProvider stu = new StudentDataProvider();
            //Insert thong tin hoc vien
            string InsStuXml = "";
            DataSet dsInsStu = stu.SelectIDNewRecord();
            stu.UpdateNewRecord();
            DataTable dtInsStu = dsInsStu.Tables[0];
            for (int i = 0; i < dtInsStu.Rows.Count; i++)
            {
                string idStu = dtInsStu.Rows[0].ItemArray[0].ToString();
                InsStuXml += stu.SelectStudentsAndConvertToXMLString(idStu);
            }
            transfDataForInsertMethod(InsStuXml, studentTb);
            //Update thong tin hoc vien
            string UpStuXml = "";
            DataSet dsUpStu = stu.SelectIDNewRecordUpdate();
            stu.UpdateNewRecordUpdate();
            DataTable dtUpStu = dsUpStu.Tables[0];
            for (int i = 0; i < dtUpStu.Rows.Count; i++)
            {
                string idStu = dtUpStu.Rows[0].ItemArray[0].ToString();
                UpStuXml += stu.SelectStudentsAndConvertToXMLString(idStu);
            }
            transfDataForUpdateMethod(UpStuXml, studentTb);
            //Delete hoc vien
            string DelStuXml = "";
            transfDataForDeleteMethod(DelStuXml, studentTb);
            //=========================================================================

            //Chuyen thong tin lop hoc cua hoc vien
            StudentInClassDataProvider stuClass = new StudentInClassDataProvider();
            //Insert lop hoc cua hoc vien
            string InsStuInClassXml = "";
            DataSet dsInsStuInClass = stuClass.SelectIDNewRecord();
            stuClass.UpdateNewRecord();
            DataTable dtInsStuInClass = dsInsStuInClass.Tables[0];
            for (int i = 0; i < dtInsStuInClass.Rows.Count; i++)
            {
                string idStu = dtInsStuInClass.Rows[i].ItemArray[0].ToString();
                string idClass = dtInsStuInClass.Rows[i].ItemArray[1].ToString();
                InsStuInClassXml += stuClass.selectClassOfStu(idStu, idClass);
            }
            transfDataForInsertMethod(InsStuInClassXml, ClassOfStu);
            //Update lop hoc cua hoc vien
            string UpStuInClassXml = "";
            DataSet dsUpStuInClass = stuClass.SelectIDNewRecordUpdate();
            stuClass.UpdateNewRecordUpdate();
            DataTable dtUpStuInClass = dsUpStuInClass.Tables[0];
            for (int i = 0; i < dtUpStuInClass.Rows.Count; i++)
            {
                string idStu = dtUpStuInClass.Rows[i].ItemArray[0].ToString();
                string idClass = dtUpStuInClass.Rows[i].ItemArray[1].ToString();
                UpStuInClassXml += stuClass.selectClassOfStu(idStu, idClass);
            }
            transfDataForUpdateMethod(UpStuInClassXml, ClassOfStu);
            //Delete lop hoc cua hoc vien
            string DelStuInClassXml = "";
            transfDataForDeleteMethod(DelStuInClassXml, ClassOfStu);
            //=========================================================================

        }

        public void GetDataFromServer()
        {
            //Lay thong tin nhan vien
            GetDataForInsertMethodWithID(EmployTb, insertMethod);
            //Lay thong tin Mon hoc
            GetDataForInsertMethodWithID(SubTb, insertMethod);
            //Lay thong tin phong hoc
            GetDataForInsertMethodWithID(RoomTb, insertMethod);
            //Lay thong tin Giao vien
            GetDataForInsertMethodWithID(TeacherTb, insertMethod);
            //Lay thong tin chuyen mon cua giao vien
            GetDataForInsertMethodWithNoneID(TeacherTeachTb, insertMethod);
            //Lay thong tin lop hoc
            GetDataForInsertMethodWithID(ClassTb, insertMethod);
            //Lay thong tin khoa hoc
            GetDataForInsertMethodWithID(CourTb, insertMethod);
            //Lay thong tinlop hoc thuoc khoa
            GetDataForInsertMethodWithNoneID(ClassInCourTb, insertMethod);
            //Lay thong tin mon hoc thuoc khoa
            GetDataForInsertMethodWithNoneID(SubInCourTb, insertMethod);
            //Lay thong tin hoc vien
            GetDataForInsertMethodWithID(studentTb, insertMethod);
            //Lay thong tin lop hoc cua hoc vien
            GetDataForInsertMethodWithNoneID(ClassOfStu, insertMethod);


            GetDataForUpdateMethodWithID(EmployTb, updateMethod);
            GetDataForUpdateMethodWithID(SubTb, updateMethod);
            GetDataForUpdateMethodWithID(RoomTb, updateMethod);
            GetDataForUpdateMethodWithID(TeacherTb, updateMethod);
            GetDataForUpdateMethodWithNoneID(TeacherTeachTb, updateMethod);
            GetDataForUpdateMethodWithID(ClassTb, updateMethod);
            GetDataForUpdateMethodWithID(CourTb, updateMethod);
            GetDataForUpdateMethodWithNoneID(ClassInCourTb, updateMethod);
            GetDataForUpdateMethodWithNoneID(SubInCourTb, updateMethod);
            GetDataForUpdateMethodWithID(studentTb, updateMethod);
            GetDataForUpdateMethodWithNoneID(ClassOfStu, updateMethod);


            GetDataForDeleteMethodWithID(EmployTb, deleteMethod);
            GetDataForDeleteMethodWithID(SubTb, deleteMethod);
            GetDataForDeleteMethodWithID(RoomTb, deleteMethod);
            GetDataForDeleteMethodWithID(TeacherTb, deleteMethod);
            GetDataForDeleteMethodWithNoneID(TeacherTeachTb, deleteMethod);
            GetDataForDeleteMethodWithID(ClassTb, deleteMethod);
            GetDataForDeleteMethodWithID(CourTb, deleteMethod);
            GetDataForDeleteMethodWithNoneID(ClassInCourTb, deleteMethod);
            GetDataForDeleteMethodWithNoneID(SubInCourTb, deleteMethod);
            GetDataForDeleteMethodWithID(studentTb, deleteMethod);
            GetDataForDeleteMethodWithNoneID(ClassOfStu, deleteMethod);
        }

        public void syncData()
        {
            while (true)
            {
                transDataToServer();
                GetDataFromServer();
                Thread.Sleep(3000);
            }
        }
    }
}
